<template>
	<a-card title="个人信息">
		<div class="landlord-profile">
			<!-- 个人信息列表 -->
			<!-- 头像 -->
			<div class="info-item">
				<div class="info-label">头像</div>
				<div class="info-content">
					<a-avatar :size="64" :src="adminInfo.logo" />
					<a-upload :showUploadList="false" :beforeUpload="beforeUpload" :customRequest="uploadLogo">
						<a-button type="link">更换</a-button>
					</a-upload>
				</div>
			</div>

			<div class="info-item">
				<div class="info-label">用户名</div>
				<div class="info-content">
					<span>{{ adminInfo.username || '未填写' }}</span>
					<a-button type="link" @click="openEditModal('username')">编辑</a-button>
				</div>
			</div>

			<div class="info-item">
				<div class="info-label">邮箱</div>
				<div class="info-content">
					<span>{{ adminInfo.email || '未填写' }}</span>
					<a-button type="link" @click="openEditModal('email')">编辑</a-button>
				</div>
			</div>

			<div class="info-item">
				<div class="info-label">电话</div>
				<div class="info-content">
					<span>{{ adminInfo.phone || '未填写' }}</span>
					<a-button type="link" @click="openEditModal('phone')">编辑</a-button>
				</div>
			</div>

			<div class="info-item">
				<div class="info-label">性别</div>
				<div class="info-content">
					<span>
						{{ adminInfo.gender === 'male' ? '男' : adminInfo.gender === 'female' ? '女' : '未填写' }}
					</span>
					<a-button type="link" @click="openEditModal('gender')">编辑</a-button>
				</div>
			</div>

		</div>

		<!-- 编辑弹窗 -->
		<a-modal
			v-model:visible="showModal"
			:title="`修改${fieldLabelMap[currentField]}`"
			@ok="saveChanges"
			cancelText="取消"
			okText="确认"
		>
			<template #default>
				<!-- 性别使用单选框 -->
				<a-radio-group v-if="currentField === 'gender'" v-model:value="editValue">
					<a-radio value="male">男</a-radio>
					<a-radio value="female">女</a-radio>
				</a-radio-group>

				<div v-else-if="currentField === 'email'">
					<a-form ref="formRef" :model="emailForm" :rules="formRules" layout="vertical">
						<a-form-item label="新邮箱" name="email">
							<a-input v-model:value="emailForm.email" placeholder="请输入新邮箱" />
						</a-form-item>
						<a-row :gutter="24">
							<a-col :span="17">
								<a-form-item label="验证码" name="code">
									<a-input v-model:value="emailForm.code" placeholder="请输入验证码" />
								</a-form-item>
							</a-col>
							<a-button @click="getEmailCode" :disabled="countDown > 0" style="margin-top: 1.9rem">
								{{ countDown > 0 ? `${countDown}s后可重新获取` : '获取验证码' }}
							</a-button>
						</a-row>
					</a-form>
				</div>
				<!-- 其他字段使用输入框 -->
				<a-input v-else v-model:value="editValue" />
			</template>
		</a-modal>
	</a-card>
</template>

<script>
	import { message } from 'ant-design-vue';
	import adminApi from "@/api/adminApi";
	import eventBus from "@/utils/eventBus";


	export default {
		data() {
			return {
				adminInfo: {
					logo: '',
					username: '',
					email: '',
					phone: '',
					gender: ''
				},
				fieldLabelMap: {
					username: '用户名',
					email: '邮箱',
					phone: '电话',
					gender: '性别'
				},
				emailForm: {
					email: '',
					code: ''
				},
				formRules: {
					email: [
						{ required: true, message: '请输入邮箱', trigger: 'blur' },
						{
							validator: (rule, value, callback) => {
								if (!this.isValidEmail(value) && value) {
									callback('请输入有效的邮箱');
								} else {
									callback(); // 校验通过
								}
							},
							trigger: 'blur'
						}
					],
					code: [
						{ required: true, message: '请输入验证码', trigger: 'blur' },
						{
							validator: (rule, value, callback) => {
								if (value.length !== 6 && value) {
									callback('验证码长度必须为6位');
								} else {
									callback(); // 校验通过
								}
							},
							trigger: 'blur'
						}
					]
				},
				showModal: false,
				currentField: '', //当前修改的字段
				editValue: '', // 编辑的值
				countDown: 0, // 验证码倒计时
				timer: null // 定时器
			};
		},
		methods: {
			//获取用户信息
			getLandlordInfo() {
				adminApi.getUserInfo()
					.then((res) => {
						this.adminInfo = res.data;
					})
					.catch((err) => {
						console.error('获取用户信息失败:', err);
					});
			},
			saveChanges() {
				// 校验手机号
				if (this.currentField === 'phone' && !this.isValidPhone(this.editValue)) {
					message.error('请输入有效的手机号');
					return; // 阻止保存操作
				}
				//如果是修改邮箱，则调用修改邮箱接口
				if (this.currentField === 'email') {
					this.$refs.formRef
						.validate()
						.then(() => {
							adminApi
								.updateEmail(this.emailForm)
								.then(() => {
									this.showModal = false;
									message.success('修改成功，请重新登录！', 1); // 1秒后自动消失
									setTimeout(() => {
										// 在消息显示完成后刷新页面
										localStorage.removeItem('satoken');
										localStorage.removeItem('name');
										window.location.reload();
									}, 1000);
								})
								.catch((err) => {
									console.error('修改失败:', err);
								});
						})
						.catch((error) => {
							console.error('表单验证失败:', error);
						});
				} else {
					this.adminInfo[this.currentField] = this.editValue;
					adminApi
						.updateUserInfo(this.adminInfo)
						.then((res) => {
							if (this.currentField === 'username'){
								localStorage.setItem('name', this.adminInfo.username)
								eventBus.emit('usernameChanged');
							}
							this.showModal = false;
							message.success('修改成功');
						})
						.catch((err) => {
							console.error('修改失败:', err);
						});
				}
			},
			// 校验手机号格式是否有效
			isValidPhone(phone) {
				const phonePattern = /^1[3-9]\d{9}$/; // 简单的手机号正则校验，支持中国手机号
				return phonePattern.test(phone);
			},
			// 校验邮箱格式
			isValidEmail(email) {
				const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
				return emailPattern.test(email);
			},
			// 获取注册验证码
			getEmailCode() {
				// 校验手机号
				if (!this.emailForm.email) {
					message.error('请输入邮箱');
					return;
				}
				if (!this.isValidEmail(this.emailForm.email)) {
					message.error('请输入有效的邮箱');
					return;
				}
				adminApi
					.getModifyEmailCode(this.emailForm.email.trim())
					.then(() => {
						message.success('验证码已发送');
						this.startCountDown();
					})
					.catch((err) => {
						console.error(err.response?.data?.message || '获取验证码失败');
					});
			},
			// 启动倒计时
			startCountDown() {
				this.countDown = 60; // 倒计时60秒
				this.timer = setInterval(() => {
					this.countDown -= 1;
					if (this.countDown <= 0) {
						clearInterval(this.timer);
					}
				}, 1000);
			},
			// 验证文件类型
			beforeUpload(file) {
				const isImage = file.type.startsWith('image/'); // 验证文件类型是否为图片
				if (!isImage) {
					message.error('只能上传图片文件!');
				}
				return isImage; // 返回 true 继续上传，false 阻止上传
			},
			// 上传头像
			uploadLogo(options) {
				const { file } = options;

				const formData = new FormData();
				formData.append('file', file);

				adminApi
					.uploadLogo(formData)
					.then((res) => {
						this.adminInfo.logo = res.data;
						message.success('头像更新成功');
					})
					.catch((err) => {
						message.error('头像上传失败:', err);
					});
			},
			openEditModal(field) {
				this.currentField = field;
				if (field === 'email') {
					this.editValue = '';
				} else {
					this.editValue = this.adminInfo[field] || '';
				}
				this.showModal = true;
			}
		},
		created() {
			this.getLandlordInfo();
		}
	};
</script>

<style scoped>
	.landlord-profile {
		padding: 20px;
	}

	.info-list {
		border-top: 1px solid #f0f2f5;
		padding-top: 20px;
	}

	.info-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 15px 0;
		border-bottom: 1px solid #f0f2f5;
	}

	.info-label {
		width: 80px;
		color: #666;
		font-weight: 500;
	}

	.info-content {
		flex: 1;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
</style>
